#pragma once
#include "Socket.hpp"
#include<functional>

using callback_t=std::function<std::string(std::string&)>;

class Server
{
private:
    void HanderRequest(std::shared_ptr<Socket> sockfd, InetAddr addr)
    {
        std::string inbuffer;
        while (true)
        {
            ssize_t n = sockfd->Recv(&inbuffer);
            if (n > 0)
            {
                LOG(LogLevel::DEBUG)<<addr.ToString()<<"# "<<inbuffer;
                std::string send_str=_cb(inbuffer);
                if(send_str.empty())
                    continue;
                sockfd->Send(send_str);
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << addr.ToString() << "读到结尾，退出";
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG)<<addr.ToString()<<"出错了，退出";
                break;
            }
        }
        sockfd->Close();
    }

public:
    Server(int port,callback_t cb)
        : _port(port), _cb(cb),_listenfd(std::make_unique<TcpSocket>())
    {
        _listenfd->BuildSocket(_port);
    }
    void Run()
    {
        while (true)
        {
            InetAddr addr;
            auto sockfd = _listenfd->Accept(&addr);
            if (sockfd == nullptr)
            {
                continue;
            }
            LOG(LogLevel::INFO) << "获取了一个新链接" << addr.ToString() << ",sockfd: " << sockfd->SockFd();
            if (fork() == 0)
            {
                // 子进程
                _listenfd->Close();
                HanderRequest(sockfd, addr);
                exit(0);
            }
            // 父进程
            sockfd->Close();
        }
    }
    ~Server() {}

private:
    uint16_t _port;
    callback_t _cb;
    std::unique_ptr<Socket> _listenfd;
};